package com.cskaoyan.gateway.controller.user;

import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IUserVerifyService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.*;
import com.mall.user.intercepter.TokenIntercepter;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: dragon-mall
 * @description: 验证登录，用户退出 需要验证登录的api
 * @author: Keyu Li
 * @create: 2021-12-13 10:08
 **/

@Slf4j
@RestController
@RequestMapping("/user")
public class LoginController {

    @Reference(timeout = 3000, retries = 0, check = false)
    IUserVerifyService verifyService;

    @GetMapping("loginOut")
    public ResponseData loginOut(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
        // 1 从 cookie中获取 token，封装 UserLogoutRequest
        UserLogoutRequest request = new UserLogoutRequest();
        String token = CookieUtil.getCookieValue(httpRequest, TokenIntercepter.ACCESS_TOKEN);
        request.setToken(token);

        // 2 service 操作: 无需service操作，直接将 HttpServletResponse中cookie设置失效
        //UserLogoutResponse response = verifyService.logout(request);

        UserLogoutResponse response = new UserLogoutResponse();
        // 3 根据 response返回
        if (true||SysRetCodeConstants.SUCCESS.getCode().equals(response.getCode())) {
            // 3.1 清除 cookie
            Cookie cookie = CookieUtil.genCookie(TokenIntercepter.ACCESS_TOKEN, null, "/", 0);
            cookie.setHttpOnly(true);
            httpResponse.addCookie(cookie);
            return new ResponseUtil<>().setData(null);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    @GetMapping("login")
    public ResponseData getLogin(HttpServletRequest httpRequest) {
        // 1 从 cookie中获取 token，封装 userGetLoginRequest
        UserGetLoginRequest request = new UserGetLoginRequest();
        String token = CookieUtil.getCookieValue(httpRequest, TokenIntercepter.ACCESS_TOKEN);
        request.setToken(token);

        // 2 service 操作
        UserGetLoginResponse response = verifyService.getLogin(request);

        // 3 根据 response返回
        if (SysRetCodeConstants.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil<>().setData(response.getGetLoginDto());
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }
}
